import store from '@/store';

const SPEED = 0.7;

export default {
  componentUpdated(el, binding) {
    if (binding.value <= binding.oldValue) return;
    const image = el.querySelector('.van-image__img');
    // 图片位置、宽高
    const {
      top: imgY,
      left: imgX,
      width: imgWidth,
      height: imgHeight,
    } = image.getBoundingClientRect();
    // 购物车位置、宽高
    const {
      top: cartY,
      left: cartX,
      width: cartWidth,
      height: cartHeight,
    } = store.state.shopCartDom.getBoundingClientRect();

    const img = image.cloneNode();
    Object.assign(img.style, {
      width: `${imgWidth}px`,
      height: `${imgHeight}px`,
    });

    const div = document.createElement('div');
    Object.assign(div.style, {
      position: 'fixed',
      top: `${imgY}px`,
      left: `${imgX}px`,
      zIndex: 999,
    });
    div.appendChild(img);

    const disX = cartX + cartWidth / 2 - imgX - imgWidth / 2;
    const disY = cartY + cartHeight / 2 - imgY - imgHeight / 2;
    const duration = SPEED * (800 - 1000 / (disX + disY));
    div.animate([{
      transform: `translateX(${disX}px)`,
    }], duration);
    img.animate([{
      transform: `translateY(${disY}px) scale(0.2)`,
    }], {
      duration,
      easing: 'cubic-bezier(.2,-0.4,.73,.04)',
    }).onfinish = () => div.remove();

    document.body.appendChild(div);
  },
};
